#include "TrueTypeFont.hpp"
#include "rect.hpp"
#include "errors.hpp"

namespace wolf
{
    int TrueTypeFont::fontSize() const
    {
        return TTF_FontHeight(font);
    }

    int TrueTypeFont::charWidth( Uint16 c )const
    {
        int width;
        TTF_GlyphMetrics(font, (Uint16)c, NULL, NULL, NULL, NULL, &width);
        return width;
    }

    void TrueTypeFont::writeChar( Uint16 c, SDL_Surface *dst, int x, int y, const Color &color )
    {
        SDL_Surface *char2Draw =TTF_RenderGlyph_Solid(font, c, color.toSDL_Color());
        int minX, maxY;
        TTF_GlyphMetrics(font, c, &minX,NULL,NULL,&maxY,NULL);
        SDL_Rect rect = {x+minX, y+TTF_FontAscent(font)-maxY, 0, 0};
        SDL_BlitSurface(char2Draw, NULL, dst, &rect);
    }

    TrueTypeFont::~TrueTypeFont()
    {
        if(autoDelete) TTF_CloseFont(font);
    }

    TrueTypeFont::TrueTypeFont( TTF_Font *font_, bool autoDelete_ )
    {
        font = font_;
        autoDelete = autoDelete_;
    }

    TrueTypeFont::TrueTypeFont( const char *file, int ptSize )
    {
        font = TTF_OpenFont(file, ptSize);
        autoDelete = true;
        if(!font)
        {
            throw SdlError(TTF_GetError());
        }
    }

}
